﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;

namespace Jeeva.ControlLibrary
{
    public class jNotifier
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        private WebClient webClient = new WebClient();
        private XmlDocument xmlDoc = new XmlDocument();
        private XmlNode node;
        private XmlNodeList nodeList;
        public List<IGmailMessage> ReceiveMails()
        {
            List<IGmailMessage> list = new List<IGmailMessage>();
            webClient.Credentials = new NetworkCredential(UserName, Password);
            string lstrResponse = Encoding.UTF8.GetString(webClient.DownloadData("https://mail.google.com/mail/feed/atom"));
            lstrResponse = lstrResponse.Replace("<feed version=\"0.3\" xmlns=\"http://purl.org/atom/ns#\">", "<feed>");
            xmlDoc.LoadXml(lstrResponse);
            node = xmlDoc.SelectSingleNode("/feed/fullcount");
            int mailCount = Convert.ToInt32(node.InnerText);

            if (mailCount > 0)
            {
                nodeList = xmlDoc.SelectNodes("/feed/entry");
                foreach (XmlNode tempnode in nodeList)
                {
                    GmailMessage message = new GmailMessage();
                    message.MessageTitle = tempnode.ChildNodes.Item(0).InnerText;
                    message.MessageFrom = tempnode.ChildNodes.Item(6).InnerText;
                    list.Add(message);
                }
            }
            return list;
        }
    }
}
